package im.composer.media.audio.stream;

import java.io.IOException;
import java.io.InputStream;

import javax.sound.sampled.AudioFormat;

import org.tritonus.share.sampled.FloatSampleBuffer;
import org.tritonus.share.sampled.FloatSampleInput;

public class FloatSampleInputStream extends InputStream {

	private final FloatSampleInput in;
	private final AudioFormat format;
	private final FloatSampleBuffer buffer;
	private final LinkedByteArrayInputStream stream = new LinkedByteArrayInputStream();

	public FloatSampleInputStream(FloatSampleInput in, AudioFormat format, int bufferSize) {
		super();
		this.in = in;
		this.format = format;
		buffer = new FloatSampleBuffer(format.getChannels(), bufferSize, format.getSampleRate());
	}

	public int available() throws IOException {
		return buffer.getByteArrayBufferSize(format);
	}

	@Override
	public int read() throws IOException {
		if (format.getFrameSize() != 1) {
			throw new IOException("cannot read a single byte if frame size > 1");
		}

		byte[] data = new byte[1];
		int temp = read(data);
		if (temp <= 0) {
			// we have a weird situation if read(byte[]) returns 0!
			return -1;
		}
		return data[0] & 0xFF;
	}

	@Override
	public int read(byte[] b, int off, int len) throws IOException {
		while (stream.available() < len) {
			stream.offer(readSamples());
		}
		return stream.read(b, off, len);
	}

	private byte[] readSamples() throws IOException {
		in.read(buffer);
		return buffer.convertToByteArray(format);
	}

}
